package com.study.common.security;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Date;
import java.util.UUID;

@SuppressWarnings("all")
public class RSAUtils {

	/**
	 * 生成公钥和私钥
	 * 
	 * @throws NoSuchAlgorithmException
	 * 
	 */
	public static KeyRepository getKeys() throws Exception {
		KeyRepository kr = new KeyRepository();
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		SecureRandom secrand = new SecureRandom(); 
		secrand.setSeed(UUID.randomUUID().toString().getBytes()); // 初始化随机产生器 
		keyPairGen.initialize(1024,secrand);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		kr.setPublicKey(publicKey);
		kr.setPrivateKey(privateKey);
		kr.setGenerateDate(new Date());
		return kr;
	}

	/**
	 * 使用模和指数生成RSA公钥
	 * 
	 * 
	 * @param modulus
	 *            模
	 * @param exponent
	 *            指数
	 * @return
	 */
	public static RSAPublicKey getPublicKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 使用模和指数生成RSA私钥
	 * 
	 * /None/NoPadding】
	 * 
	 * @param modulus
	 *            模
	 * @param exponent
	 *            指数
	 * @return
	 */
	public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 公钥加密 使用填充算法, 可造成相同原文每次加密产生的密文不一致 
	 * 需要与解密算法相同 默认 非填充
	 * 
	 * @param data
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
			throws Exception {
		//"RSA/None/NoPadding" 非填充
		//"RSA/None/PKCS1Padding" 填充随机数
		Cipher cipher = Cipher.getInstance("RSA",
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		// 模长
		int key_len = publicKey.getModulus().bitLength() / 8;
		// 加密数据长度 <= 模长-11
		String[] datas = splitString(data, key_len - 11);
		String mi = "";
		// 如果明文长度大于模长-11则要分组加密
		for (String s : datas) {
			mi += bcd2Str(cipher.doFinal(s.getBytes()));
		}
		return mi;
	}

	/**
	 * 私钥解密
	 * 
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPrivateKey(String data,
			RSAPrivateKey privateKey) throws Exception {
		//"RSA/None/NoPadding" 非填充
		//"RSA/None/PKCS1Padding" 填充随机数 RSA/ECB/PKCS1Padding
		Cipher cipher = Cipher.getInstance("RSA",
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		// 模长
		int key_len = privateKey.getModulus().bitLength() / 8;
		byte[] bytes = data.getBytes();
		byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
		// System.err.println(bcd.length);
		// 如果密文长度大于模长则要分组解密
		String ming = "";
		byte[][] arrays = splitArray(bcd, key_len);
		for (byte[] arr : arrays) {
			ming += new String(cipher.doFinal(arr));
		}
		return ming;
	}
	
	/**
	 * 前端jsRSA, 解码
	 *<pre> </pre>
	 * @param data
	 * @param keyR
	 * @return
	 */
	public static String decryptRSAforJS(String data ,KeyRepository keyR)  {
		try {
			if (keyR == null || data==null ||data.isEmpty()) {
				return "";
			}
			RSAPrivateKey privateKey = keyR.getPrivateKey();
			String[] str = data.split(" ");// 受限加密字段长度, 以空格做分割
			String res = "";
			if (str != null && str.length > 0) {
				for (String string : str) {
					if (string == null || string.isEmpty()) {
						continue;
					}
					res = res
							+ printReverse(RSAUtils.decryptByPrivateKey(string,
									privateKey));
				}
			}
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	private static String printReverse(String s) {
		if(s == null){
			return "";
		}
		StringBuilder sb = new StringBuilder(s);
		sb.reverse();
		return sb.toString();
	}

	/**
	 * ASCII码转BCD码
	 * 
	 */
	public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
		byte[] bcd = new byte[asc_len / 2];
		int j = 0;
		for (int i = 0; i < (asc_len + 1) / 2; i++) {
			bcd[i] = asc_to_bcd(ascii[j++]);
			bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
		}
		return bcd;
	}

	public static byte asc_to_bcd(byte asc) {
		byte bcd;

		if ((asc >= '0') && (asc <= '9'))
			bcd = (byte) (asc - '0');
		else if ((asc >= 'A') && (asc <= 'F'))
			bcd = (byte) (asc - 'A' + 10);
		else if ((asc >= 'a') && (asc <= 'f'))
			bcd = (byte) (asc - 'a' + 10);
		else
			bcd = (byte) (asc - 48);
		return bcd;
	}

	/**
	 * BCD转字符串
	 */
	public static String bcd2Str(byte[] bytes) {
		char temp[] = new char[bytes.length * 2], val;

		for (int i = 0; i < bytes.length; i++) {
			val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
			temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

			val = (char) (bytes[i] & 0x0f);
			temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
		}
		return new String(temp);
	}

	/**
	 * 拆分字符串
	 */
	public static String[] splitString(String string, int len) {
		int x = string.length() / len;
		int y = string.length() % len;
		int z = 0;
		if (y != 0) {
			z = 1;
		}
		String[] strings = new String[x + z];
		String str = "";
		for (int i = 0; i < x + z; i++) {
			if (i == x + z - 1 && y != 0) {
				str = string.substring(i * len, i * len + y);
			} else {
				str = string.substring(i * len, i * len + len);
			}
			strings[i] = str;
		}
		return strings;
	}

	/**
	 * 拆分数组
	 */
	public static byte[][] splitArray(byte[] data, int len) {
		int x = data.length / len;
		int y = data.length % len;
		int z = 0;
		if (y != 0) {
			z = 1;
		}
		byte[][] arrays = new byte[x + z][];
		byte[] arr;
		for (int i = 0; i < x + z; i++) {
			arr = new byte[len];
			if (i == x + z - 1 && y != 0) {
				System.arraycopy(data, i * len, arr, 0, y);
			} else {
				System.arraycopy(data, i * len, arr, 0, len);
			}
			arrays[i] = arr;
		}
		return arrays;
	}

	public static void main(String[] args) throws Exception {
		KeyRepository kr = getKeys();
		// 生成公钥和私钥
		RSAPublicKey publicKey = kr.getPublicKey();
		RSAPrivateKey privateKey = kr.getPrivateKey();

		// 模
		String modulus = publicKey.getModulus().toString();
		System.out.println("pubkey modulus=" + modulus);
		// 公钥指数
		String public_exponent = publicKey.getPublicExponent().toString();
		System.out.println("pubkey exponent=" + public_exponent);
		// 私钥指数
		String private_exponent = privateKey.getPrivateExponent().toString();
		System.out.println("private exponent=" + private_exponent);
		
		modulus="115005757644997083071299295569684987339342819535707674504272379938062295294750670071695274618819497047638185914835584527443838730131871309244116166279218204130204439148148371016444444675076969248010093418371434440221011710866574381943208337893291499663313470758584620037134739856901675018647265024279664112717";
		public_exponent="65537";
		private_exponent="5604900894427890860578451104712969003186916788944417845898438767752124314073479716938442515411286350766076656117687061975000700429394036372212750585101894736679373262690761858078117581239211700555446625259744918489902499302952773161467917464393191826670265171197030250914350125962559814312378018510124732993";

		// 明文
		String ming = "djf%e5%9b%9b%e5%a4%a7%e5%8f%91%e9%80%81%e5%88%b0%e6%b3%95%e6%8b%89%e7%ac%ac%e9%85%b8%e8%be%a3%e7%b2%89%e5%bb%ba%e8%ae%be%e5%a4%a7%e8%b7%af%e5%90%a6%e5%86%b3%e4%ba%86%e9%80%9f%e5%ba%a6%e5%bf%ab%e9%a3%93%e9%a3%8e%e6%a1%91%e8%bf%aa%e8%b7%af%e5%8f%a3%e8%a7%81%e5%88%86%e8%b7%af%e5%8f%a3%e8%a7%81%e7%88%b1%e7%9a%84%e8%89%b2%e6%94%be";
		// 使用模和指数生成公钥和私钥
		RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
		
		System.out.println("pubkey modulus=" +pubKey.getModulus() .toString(16));
		System.out.println("pubkey exponent=" +pubKey.getPublicExponent().toString(16));
		RSAPrivateKey priKey = RSAUtils
				.getPrivateKey(modulus, private_exponent);
		// 加密后的密文
		String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
		System.err.println("mi=" + mi);
		
		mi ="364d2b8a971872518d7cba39f153010ce95abb5cb407ff1b9d1535b4cf02df5fd8d6eb3bdcc604db5e5a5ceb0b8aba14c8984f74ba86c09ac40b7cc7524b9096d20e4734e0f6b5ef5c2f22bbeceeb90ccfea86363df88f200b97bd3e4b70d7f5eed3fb6a87365c1a318bb6ac8603cf0759fe7c560874df4235280c10a5a0bd8224ce309255833ce3d2554e64e07baac3a9b8bcbe27280d1dd2929a8b680f91f06d8cfc73f12b018fad8e093c7d3a9cce8df953d2c6eb5fb0da88b7ad1e1396b8a8fc964b45089e5cc919e793cb06a62c7395cca7410199334c76e21458ed38452245d1369a565b9dc9f27792bfa3233a38787e19350e5a2556c6460882186fa576cecd3f27fd60e51bda8b1a5e17fb25c0f03f5af2265b7f4dae98d703a9f6c4ae8c14131d9c19c17f8303f92f421962aa6d81272bf667678c7d9f6761cc2897b106871e67a930751e8123c825080d0cc0e166728db8f88b335a3658bf16cea42fd08086619745bd7f566de15f749114056b5223ae62acac9225ac8fe7d0a2c2";
		// 解密后的明文
		String ming2 = RSAUtils.decryptByPrivateKey(mi, priKey);
		System.err.println("ming2=" + ming2);
	}
}